<?php

namespace Albireo\OAuthServer;

use Nette\Object;
use \dibi;

class Consumer extends Object implements IConsumer {

    private $id;
    private $key;
    private $secret;
    private $active;

    public static function findByKey($key) {
        $consumer = null;
        $info = dibi::query("select app_id from applications where app_key = %s", $key);
        if ($info->rowCount() == 1) {
            $info = $info->fetch();
            $consumer = new Consumer($info['app_id']);
        }
        return $consumer;
    }

    public function __construct($id = 0) {
        if ($id != 0) {
            $this->id = $id;
            $this->load();
        }
    }

    private function load() {
        $info = dibi::fetch("select * from applications where app_id = '" . $this->id . "'");
        $this->key = $info['app_key'];
        if ($info['app_secret'] == NULL) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://localhost/cmp/www/check/?key=".$this->id."&secret=3ac974d4a0264dd785a512ea1fe65008ca49a9c5");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($ch);
            \Nette\Debug::dump($output);
        }
        $this->secret = $info['app_secret'];
        $this->active = $info['app_active'];
    }

    public static function create($key, $secret) {
        //TODO: fix for our DB
        dibi::query("insert into applications(consumer_key,consumer_secret,active) values ('" . $key . "','" . $secret . "',1)");
        return new Consumer(dibi::getInsertId());
    }

    public function isActive() {
        return $this->active;
    }

    public function getKey() {
        return $this->key;
    }

    public function getSecretKey() {
        return $this->secret;
    }

    public function getId() {
        return $this->id;
    }

    public function hasNonce($nonce) {
        $check = dibi::fetch("select count(*) as cnt from app_nonce where nonce = '" . $nonce . "' and app_id = " . $this->id);
        if ($check['cnt'] == 1) {
            return true;
        } else {
            return false;
        }
    }

    public function addNonce($nonce) {
        dibi::query("insert into app_nonce (app_id,timestamp,nonce) values (" . $this->id . "," . time() . ",'" . $nonce . "')");
    }

    /* setters */

    public function setKey($key) {
        $this->key = $key;
    }

    public function setSecret($secret) {
        $this->secret = $secret;
    }

    public function setActive($active) {
        $this->active = $active;
    }

    public function setId($id) {
        $this->id = $id;
    }

}